<template>
	<view class="search-blog-container">
		<view class="search-bar-box">
			<!-- 自定义组件的 v-model 2.2.2 新增 -->
			<my-search
			 v-model="searchVal"
			 :placeholderText="defaultText"
			 :ifShowInput="true"
			 :config="{
					backgroundColor: '#f1f0f3'
			  }"
				@search="onSearchConfirm"
				@focus="onSearchFocus"
				@blur="onSearchBlur"
				@clear="onSearchClear"
				@cancel="onSearchCancel"
				/>
			<!-- 热搜列表 -->
			<view class="search-hot-list-box card" v-if="showType === HOT_LIST">
				<!-- 列表 -->
				<search-hot-list @onSearch="onSearchConfirm" />
			</view>
			<!-- 搜索历史 -->
			<view class="search-history-box" @onItemClick="onSearchConfirm" v-else-if="showType === SEARCH_HISTORY">
				<search-history />
			</view>
			<!-- 搜索结果 -->
			<view class="search-result-box" v-else>
				<!-- 1. 给mescroll-body的组件添加: ref="mescrollItem" (固定的,不可改,与mescroll-comp.js对应)-->
			 <search-result-list ref="mescrollItem" :queryStr='searchVal' />
			</view>
		</view>
	</view>
</template>

<script>
	// 2. 引入mescroll-comp.js
	import MescrollCompMixin from '@/uni_modules/mescroll-uni/components/mescroll-uni/mixins/mescroll-comp.js';
	import { _getDefaultText } from 'api/search.js'
	import { mapMutations } from 'vuex'
	// 0 ：热搜列表默认
	const HOT_LIST = '0'
	// 1：搜索历史
	const SEARCH_HISTORY = '1';
	// 2：搜索结果
	const SEARCH_RESULT = '2';
	export default {
		mixins: [MescrollCompMixin],
		data() {
			return {
				HOT_LIST,
				SEARCH_HISTORY,
				SEARCH_RESULT,
				showType: HOT_LIST,
				defaultText: '默认的placeholderText',
				searchVal: '', // 绑定输入框中的内容
			}
		},
		methods: {
			...mapMutations('search', ['addSearchData']),
			/**
			 * 获取推荐搜索文本
			 */
			async loadDefaultText() {
				const { data: res } = await _getDefaultText()
				this.defaultText = res.defaultText
			},
			/**
			 * 搜索内容
			 */
			onSearchConfirm(val) {
				console.log(val)
				// 当用户未输入任何内容时 点击搜索 搜索推荐的内容
				this.searchVal = val ? val : this.defaultText
				this.addSearchData(this.searchVal);
				// 保存搜索历史数据
				if (this.searchVal) {
					this.showType = SEARCH_RESULT
				}
			},
			// searchbar 获取焦点
			onSearchFocus(val) {
				console.log('获取焦点');
				this.showType = SEARCH_HISTORY;
			},
			/**
			 * searchbar 失去焦点
			 */
			onSearchBlur(val) {
			},
			/**
			 * searchbar 清空内容
			 */
			onSearchClear() {
				console.log('searchbar 清空内容');
			},
			/**
			 * searchbar 取消按钮
			 */
			onSearchCancel(val) {
				this.showType = HOT_LIST
				console.log('searchbar 取消按钮');
			}
		},
		created() {
			this.loadDefaultText()
		}
	}
</script>

<style lang="scss" scoped>
	.search-blog-container {
		.search-bar-box {
			background-color: $uni-bg-color;
			padding: $uni-spacing-row-sm;
			position: sticky;
			top: 0px;
			z-index: 9;
		}
	}
</style>
